package com.mediacloud.app.newsmodule.activity.military_encyclopedia

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.view.ViewStub
import android.webkit.*
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eventTrack.TXReportManager
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.pictureselector.GlideEngine
import com.mediacloud.app.appfactory.cache.AppConfig
import com.mediacloud.app.assembly.util.*
import com.mediacloud.app.assembly.views.FontResizeView
import com.mediacloud.app.model.CommentCommitPushEvent
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil.invokeStoragePermission
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleItemReciver
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.model.view.WebBrowser
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.StyleSetActivity
import com.mediacloud.app.newsmodule.activity.WebViewPageActivity
import com.mediacloud.app.newsmodule.fragment.baoliao.api.CMSApi
import com.mediacloud.app.newsmodule.fragment.baoliao.api.ProgressRequestBody.UploadCallbacks
import com.mediacloud.app.newsmodule.fragment.baoliao.model.LocalMediaWithState
import com.mediacloud.app.newsmodule.fragment.baoliao.model.add.SubmitImageReturnData
import com.mediacloud.app.newsmodule.fragment.imagetext.*
import com.mediacloud.app.newsmodule.utils.*
import com.mediacloud.app.newsmodule.utils.share.OnShareClickListener
import com.mediacloud.app.newsmodule.utils.share.ShareWrap
import com.mediacloud.app.newsmodule.view.FontResizeDialog
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.mediacloud.app.user.model.UserInfo
import com.tencent.mmkv.MMKV
import com.utils.ClickUtils
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_detail_military_ency_detail.*
import kotlinx.coroutines.*
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import org.jsoup.Jsoup
import org.jsoup.select.Elements
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.List
import kotlin.collections.MutableList
import kotlin.collections.MutableMap
import kotlin.collections.arrayListOf
import kotlin.collections.forEach
import kotlin.collections.indices
import kotlin.collections.isNotEmpty
import kotlin.collections.mutableListOf
import kotlin.collections.mutableMapOf
import kotlin.collections.set


/**
 * 军事百科详情页
 */
class MilitaryEncyclopediaDetailActivity : StyleSetActivity(), FontResizeView.OnFontChangeListener {


    var mTyReportStartTime: Long = 0
    var mTyReportEndTime: Long = 0
    var broccoliView: View? = null
    var article_id: Long = 0
    var militaryEncyclopediaDirectoryRelationAdapter: MilitaryEncyclopediaDirectoryRelationAdapter? = null
    var militaryEncyclopediaInfoRelationAdapter: MilitaryEncyclopediaInfoRelationAdapter? = null
    var militaryEncyclopediaEntryRefAdapter: MilitaryEncyclopediaEntryRefAdapter? = null

    companion object {
        val ARTICLE_ID: String = "article_id"
        val SPECIAL_ID: String = "special_id"
    }

    override fun getLayoutResID(): Int {
        return R.layout.activity_detail_military_ency_detail
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        article_id = intent.getLongExtra(ARTICLE_ID, 0)
        var specialId = intent.getLongExtra(SPECIAL_ID, 0)
        loadingView = Utility.findViewById(mRootView, R.id.mLoadingView)
        setTitle("军事百科")
        initViewStub()
        if (specialId != 0L){//从专题词条点击过来的，展示图谱
            getSpecialArticles(specialId)
        }
        getDetail()
       // getNewsDetail()
        articleItem.type = 37
    }

    private fun getSpecialArticles(specialId: Long) {
        DataInvokeUtil.getZiMeiTiApi()
            .getWikiSpecial(specialId,1,1,100)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {

                }
                override fun onNext(json: JSONObject) {
                    if (json.optBoolean("state")) {
                        val data = json.optJSONObject("data")
                        val meta = data.optJSONArray("meta")
                        val special = data.optJSONObject("special")
                        //专题义项军事图谱
                        meta?.let{
                            val list = mutableListOf<ArticleItem>()
                            for (i in 0 until meta.length()) {
                                var item = ArticleItem()
                                val optJSONObject = meta.optJSONObject(i)
                                item.logo = optJSONObject.optString("logo")
                                item.type = optJSONObject.optInt("type")
                                item.id = optJSONObject.optLong("id")
                                item.title = optJSONObject.optString("title")
                                item.shortTitle = optJSONObject.optString("shortTitle")
                                list.add(item)
                            }
                            if (list.isNotEmpty()) {
                                val vsTopicTopLayout = findViewById<ViewStub>(R.id.vsTopicTopLayout)
                                vsTopicTopLayout.inflate()
                                val tvShortTitle = findViewById<TextView>(R.id.tvShortTitle)
                                val rvTopicTop = findViewById<RecyclerView>(R.id.rvTopicTop)
                                val specialArticle =
                                    Gson().fromJson(special.toString(), SpecialArticle::class.java)
                                tvShortTitle.text = specialArticle?.name
                                rvTopicTop.layoutManager =
                                    ViewUtils.generateRecyclerLinearLayoutManager(this@MilitaryEncyclopediaDetailActivity, false)
                                val militaryEncyclopediaTopicTopAdapter = MilitaryEncyclopediaTopicTopAdapter()
                                rvTopicTop.adapter = militaryEncyclopediaTopicTopAdapter
                                militaryEncyclopediaTopicTopAdapter.articleId = article_id
                                militaryEncyclopediaTopicTopAdapter.setNewData(list)
                                militaryEncyclopediaTopicTopAdapter.setOnItemClickListener { adapter, view, position ->
                                    ClickUtils.delayClickable(view)
                                    val item = adapter.getItem(position) as ArticleItem
                                    item.specialId = specialArticle.id
                                    item.isCloseActivity = false
                                    NewsItemClickUtils.OpenItemNewsHandle(view.context, item.type, item, null)
                                }
                            }
                        }


                    }
                }

                override fun onError(e: Throwable) {

                }

                override fun onComplete() {

                }

            })
    }

    private fun initViewStub() {
        val vs = findViewById<ViewStub>(R.id.vsBroccoli)
        vs.inflate()
        broccoliView = findViewById(R.id.broccoli)
    }

    private fun getDetail() {
        DataInvokeUtil.getZiMeiTiApi()
            .getContentEntry(article_id)
            .map {
                val t =
                    Gson().fromJson(it.toString(), MilitaryEncylopediaResultBean::class.java)
                   if(t.state){
                      try {
                          val detail = ArticleItemReciver()
                          val metaJson = JSONObject()
                          metaJson.put("state",true)
                          val data = JSONObject()
                          data.put("meta",it.optJSONObject("data")?.optJSONObject("detail"))
                          metaJson.put("data",data)
                          detail.readFromJson(metaJson)
                        t.data.item = detail.articleItem
                      }catch (e:Exception){
                          e.printStackTrace()
                      }
                   }
                t
            }
            .onErrorReturn { null }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<MilitaryEncylopediaResultBean> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(t :MilitaryEncylopediaResultBean) {

                    if (t.state) {
                        broccoliView?.visibility = View.GONE
                        val data = t.data
                        mTyReportStartTime = System.currentTimeMillis()
                        mTyReportEndTime = mTyReportStartTime
                        updateView(data)
                        articleItem = data.item
                        TXReportManager.getInstance().view_wiki(articleItem)
                        initView()
                    }else{
                        initView()
                    }
                }

                override fun onError(e: Throwable) {
                    initView()
                    broccoliView?.visibility = View.GONE
                    showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                }

                override fun onComplete() {

                }


            })

    }

    var entryRefList: List<EntryRefList>?=null//参考资料
    var linkRelationList: List<LinkRelationList>?=null//相关引用词条

    @SuppressLint("SetJavaScriptEnabled")
    private fun updateView(data: MilitaryEncylopediaResult) {
        entryRefList = data.entryRefList
        linkRelationList = data.linkRelationList
        //图集
        data.imageSimpleList?.let {
            var urlList = arrayListOf<String>()
            it.forEach { urlList.add(it.url) }
            if (it.isNotEmpty()) {
                imagesRv.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(this, false)
                val militaryEncyclopediaImageAdapter = MilitaryEncyclopediaImageAdapter()
                imagesRv.adapter = militaryEncyclopediaImageAdapter
                militaryEncyclopediaImageAdapter.setNewData(it)
                militaryEncyclopediaImageAdapter.setOnItemClickListener { adapter, view, position ->
                    ClickUtils.delayClickable(view)
                    if (isFastClick()) {
                        val intent = Intent(view.context, WikiPhotoDetailActivity::class.java)
                        intent.putExtra("photos", urlList)
                        intent.putExtra("index", position)
                        view.context.startActivity(intent)
                    }
                }
            }

        }
        //名称
        tvTitle.text = data.title
        tvShortTitle.text = data.shortTitle
        //义项
        data.simpleInfoDtoList?.let { info ->
            if (info.isNotEmpty() && info.size > 1)
                rlMore.visibility = View.VISIBLE
            tvMeanings.text = "${data.title}是多义词，共${info.size}个义项"
            val meaningsDialog = MeaningsDialog(this)
            rlMore.setOnClickListener {
                meaningsDialog.show(article_id, tvMeanings.text.toString(), info)
            }

        }

        //内容
        parseHtml(data.content)
        //信息项
        data.entryInfoRelationList?.let {
            if (it.isNotEmpty()) {
                val layoutManager =
                    ViewUtils.generateRecyclerLinearLayoutManager(this, true)

                militaryEncyclopediaInfoRelationAdapter = MilitaryEncyclopediaInfoRelationAdapter()

                militaryEncyclopediaInfoRelationAdapter?.setNewData(it)

                if (it.size > 5) {
                    militaryEncyclopediaInfoRelationAdapter?.setShowOnlyCount(true)
                    layoutFold.visibility = View.VISIBLE
                    layoutFold.setOnClickListener {
                        ClickUtils.delayClickable(it)
                        if (tvEllipsize.text == "展开") {
                            tvEllipsize.text = "收起"
                            ivEllipsize.setImageResource(R.drawable.ic_bk_detail_up)
                            militaryEncyclopediaInfoRelationAdapter?.setShowOnlyCount(false)
                        } else {
                            tvEllipsize.text = "展开"
                            ivEllipsize.setImageResource(R.drawable.ic_bk_detail_down)
                            militaryEncyclopediaInfoRelationAdapter?.setShowOnlyCount(true)
                        }

                    }
                } else {
                    layoutFold.visibility = View.GONE
                }
                layoutManager.isSmoothScrollbarEnabled = true
                layoutManager.isAutoMeasureEnabled = true
                introduceRv.layoutManager = layoutManager
                introduceRv.setHasFixedSize(true)
                introduceRv.isNestedScrollingEnabled = false
                introduceRv.adapter = militaryEncyclopediaInfoRelationAdapter
            }
        }
        //相关视频
        data.relativeVideoList?.let {
            if (it.isNotEmpty()) {
                val layoutRelativeVideo = findViewById<ViewStub>(R.id.layoutVideo)
                layoutRelativeVideo.inflate()
                val rvRelativeVideo = findViewById<RecyclerView>(R.id.rvRelativeVideo)
                rvRelativeVideo.layoutManager =
                    ViewUtils.generateRecyclerLinearLayoutManager(this, false)
                val militaryEncyclopediaVideoRelationAdapter =
                    MilitaryEncyclopediaVideoRelationAdapter()
                rvRelativeVideo.adapter = militaryEncyclopediaVideoRelationAdapter
                militaryEncyclopediaVideoRelationAdapter.setNewData(it)
                militaryEncyclopediaVideoRelationAdapter.setOnItemClickListener { adapter, view, position ->
                    ClickUtils.delayClickable(view)
                    val item = adapter.getItem(position) as RelativeVideoList
                    var intent = Intent(
                        this@MilitaryEncyclopediaDetailActivity,
                        WikiVideoPlayActivity::class.java
                    )
                    intent.putExtra("playUrl", item.tsAddress[0].url)
                    intent.putExtra("logo", item.poster)
                    intent.putExtra("Duration", item.duration)
                    startActivity(intent)
                }
            }
        }
        //相关专题词条
        data?.relativeCatalogList?.let {
            if (it.isNotEmpty()) {
                val layoutRelativeTopic = findViewById<ViewStub>(R.id.layoutTopic)
                layoutRelativeTopic.inflate()
                val rvRelativeTopic = findViewById<RecyclerView>(R.id.rvRelativeTopic)
                rvRelativeTopic.layoutManager =
                    ViewUtils.generateRecyclerLinearLayoutManager(this, false)
                val militaryEncyclopediaTopicRelationAdapter =
                    MilitaryEncyclopediaTopicRelationAdapter()
                rvRelativeTopic.adapter = militaryEncyclopediaTopicRelationAdapter
                militaryEncyclopediaTopicRelationAdapter.setNewData(it)
                militaryEncyclopediaTopicRelationAdapter.setOnItemChildClickListener { adapter, view, position ->
                    ClickUtils.delayClickable(view)
                    val item = adapter.getItem(position) as RelativeCatalogList
                    var articleItem = ArticleItem()
                    articleItem.specialId = item.specialId
                    if (view.id == R.id.tvMore) {//更多
                        WebViewPageActivity.start(
                            "",
                            item.url,
                            this@MilitaryEncyclopediaDetailActivity
                        )
                    } else if (view.id == R.id.layoutContent3) {
                        articleItem.id = item.articles[2].articleId
                        articleItem.type = item.articles[2].type
                        NewsItemClickUtils.OpenItemNewsHandle(view.context, articleItem.type, articleItem, null)
                    } else if (view.id == R.id.layoutContent2) {
                        articleItem.id = item.articles[1].articleId
                        articleItem.type = item.articles[1].type
                        NewsItemClickUtils.OpenItemNewsHandle(view.context, articleItem.type, articleItem, null)
                    } else if (view.id == R.id.layoutContent1) {
                        articleItem.id = item.articles[0].articleId
                        articleItem.type = item.articles[0].type
                        NewsItemClickUtils.OpenItemNewsHandle(view.context, articleItem.type, articleItem, null)
                    }

                }
            }
        }
        //相关词条
        data?.relativeEntryList?.let {
            if (it.isNotEmpty()) {
                val layoutRelativeNormal = findViewById<ViewStub>(R.id.layoutNormal)
                layoutRelativeNormal.inflate()
                val rvRelativeNormal = findViewById<RecyclerView>(R.id.rvRelativeNormal)
                rvRelativeNormal.layoutManager =
                    ViewUtils.generateRecyclerLinearLayoutManager(this, true)
                val militaryEncyclopediaNormalRelationAdapter =
                    MilitaryEncyclopediaNormalRelationAdapter()
                rvRelativeNormal.adapter = militaryEncyclopediaNormalRelationAdapter
                militaryEncyclopediaNormalRelationAdapter.setNewData(it)
                militaryEncyclopediaNormalRelationAdapter.setOnItemClickListener { adapter, view, position ->
                    ClickUtils.delayClickable(view)
                    val item = adapter.getItem(position) as RelativeEntryList
                    var articleItem = ArticleItem()
                    articleItem.id = item.articleId
                    articleItem.type = item.type
                    NewsItemClickUtils.OpenItemNewsHandle(view.context, item.type, articleItem, null)
                }
            }
        }
        //百科章节
        data.entryDirectoryRelationList?.let { list ->
            if (list.isNotEmpty()) {
                val directoryTab = findViewById<TabLayout>(R.id.directoryTab)
                val rvDirectory = findViewById<RecyclerView>(R.id.rvDirectory)

                rvDirectory.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(this, true)
                militaryEncyclopediaDirectoryRelationAdapter =
                    MilitaryEncyclopediaDirectoryRelationAdapter()
                militaryEncyclopediaDirectoryRelationAdapter?.entryRefList = entryRefList
                militaryEncyclopediaDirectoryRelationAdapter?.linkRelationList = linkRelationList
                rvDirectory.adapter = militaryEncyclopediaDirectoryRelationAdapter
                militaryEncyclopediaDirectoryRelationAdapter?.setNewData(list)

                for (i in list.indices)
                directoryTab.addTab(directoryTab.newTab().setText(list[i].directoryName))
                directoryTab.tabMode = TabLayout.MODE_SCROLLABLE
                directoryTab.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.cctv7_red))
                directoryTab.setTabTextColors(ContextCompat.getColor(this, R.color._222), ContextCompat.getColor(this, R.color.cctv7_red))

                //联动
                directoryTab.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                    override fun onTabSelected(tab: TabLayout.Tab) {
                        appbarLayout.setExpanded(false)
                        mScrollView.smoothScrollTo(0, rvDirectory.getChildAt(tab.position).top + rvDirectory.top)
                    }
                    override fun onTabUnselected(tab: TabLayout.Tab) {
                    }

                    override fun onTabReselected(tab: TabLayout.Tab) {
                    }

                })
                mScrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                    for (i in list.size-1 downTo 0){
                        if (scrollY >= rvDirectory.top + rvDirectory.getChildAt(i).top) {
                            // 跳转到指定的 tab
                            directoryTab.setScrollPosition(i, 0f, true)
                            break
                        }
                    }

                })

            }

        }
        //纠错
        errorCorrectingDialog = ErrorCorrectingDialog(this)
        errorCorrectingDialog?.recyclerView?.let {
            it.layoutManager = GridLayoutManager(it.context, 3)
            imgAdapter = ErrorCorrectingAdapter(it.context,
                object : ErrorCorrectingAdapter.OnDeleteListener {
                    override fun onDelete(deleteItem: LocalMediaWithState?) {
                        imageList.clear()
                        imgAdapter?.selectList?.let { list ->
                            if (list[list.size - 1].localMedia != null) {
                                imageList.addAll(list)
                            } else imageList.addAll(list.subList(0, list.size - 1))
                            imgAdapter?.setSelectList(imageList)
                        }
                        errorCorrectingDialog?.let {
                            it.tvUpNum?.text = "(${imageList.size}/9)"
                        }

                    }

                    override fun onClickItem() {
                        invokeStoragePermission(
                            this@MilitaryEncyclopediaDetailActivity,
                            object : IPermissionsAgree {
                                override fun onAgree() {
                                    permissionsOK(PictureConfig.TYPE_IMAGE)
                                }

                                override fun onRefuse() {}
                                override fun hasPermissions() {
                                    permissionsOK(PictureConfig.TYPE_IMAGE)
                                }
                            })
                    }

                })
            it.adapter = imgAdapter
            imgAdapter?.setSelectList(imageList)

        }

        errorCorrectingDialog?.callBack = object : ErrorCorrectingDialog.ItemClickListener {
            override fun submit(content: String) {
                submitImage(content)
            }

        }
        errorCorrectingDialog?.setOnDismissListener {
            imageList.clear()
            imgAdapter?.selectList?.clear()
            imgAdapter?.setSelectList(imageList)
            resourceModes.clear()
            errorCorrectingDialog?.let {
                it.etCorrectContent?.setText("")
                it.tvUpNum?.text = "(${imageList.size}/9)"
            }
        }
        tvErrorCorrecting.setOnClickListener {
            if (UserInfo.isLogin(this)) {
                errorCorrectingDialog?.show()
            } else {
                LoginUtils.request_source="纠错";
                LoginUtils.invokeLogin(this)
            }
        }
        //参考资料
        data.entryRefList?.let {
            if (it.isNotEmpty()){
                val layoutReferences = findViewById<ViewStub>(R.id.layoutReferences)
                layoutReferences.inflate()
                val rvResources = findViewById<RecyclerView>(R.id.rvResources)
                rvResources.layoutManager = ViewUtils.generateRecyclerLinearLayoutManager(this, true)
                militaryEncyclopediaEntryRefAdapter = MilitaryEncyclopediaEntryRefAdapter()
                rvResources.adapter = militaryEncyclopediaEntryRefAdapter
                militaryEncyclopediaEntryRefAdapter?.setNewData(it)
                militaryEncyclopediaEntryRefAdapter?.setOnItemClickListener { adapter, view, position ->
                    ClickUtils.delayClickable(view)
                    val item = adapter.getItem(position) as EntryRefList
                    WebViewPageActivity.start(item.websiteName, item.websiteUrl, this@MilitaryEncyclopediaDetailActivity)
                }
            }

        }

    }

    /**
     * 纠错提交
     * @param content String
     */
    private fun submitErrorCorrect(content: String) {
        TXReportManager.getInstance().wiki_correction(articleItem)
        var map: MutableMap<String, Any> = mutableMapOf()
        val userInfo = UserInfo.getUserInfo(this@MilitaryEncyclopediaDetailActivity)
        map["article_id"] = article_id
        map["content"] = content
        map["image_list"] = Gson().toJson(resourceModes)
        map["user_id"] = userInfo.userid
        map["user_name"] = userInfo.nickname
        map["avatar"] = userInfo.avatar

        DataInvokeUtil.getZiMeiTiApi()
            .errorCorrect(map)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<JSONObject> {
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(t: JSONObject) {
                    if (t.optBoolean("state")) {
                        errorCorrectingDialog?.dismiss()
                        ToastUtil.showCustomView(this@MilitaryEncyclopediaDetailActivity, "提交成功")
                    } else {
                        ToastUtil.showCustomView(this@MilitaryEncyclopediaDetailActivity, "网络异常，请检查网络")

                    }
                }

                override fun onError(e: Throwable) {
                    ToastUtil.showCustomView(this@MilitaryEncyclopediaDetailActivity, "网络异常，请检查网络")
                }

                override fun onComplete() {

                }

            })
    }

    private fun getNewsDetail() {
        val newsDetailInvoker = NewsDetailInvoker(object : DataInvokeCallBack<ArticleItemReciver> {
            override fun success(data: ArticleItemReciver?) {
                data?.let {
                    if (it.state) {
                        articleItem = it.articleItem
                        initView()
                    } else {
                        initView()
                    }
                }
            }

            override fun fault(data: Any?) {
                initView()
            }
        })
        newsDetailInvoker?.getArticleById("" + article_id, "")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    private fun commentCommitPush(data: CommentCommitPushEvent) {
        collectComment(data.content, data.beReplayUserName, data.beReplayUserId)
    }

    private fun initView() {

        refreshBottomStyle(articleItem, 1)
        fontShare?.init(articleItem, catalogItem, object : OnShareClickListener {
            override fun onSharePraiseClick() {
                TXReportManager.getInstance().like_comment(articleItem)
            }
            override fun onShareCommentClick() {
                TXReportManager.getInstance().like_comment(articleItem)
            }
            override fun onShareCollectionClick() {
                TXReportManager.getInstance().like_comment(articleItem)
            }
            override fun onTextFontClick() {
                if (fontResizeDialog == null) {
                    fontResizeDialog =
                        FontResizeDialog(
                            this@MilitaryEncyclopediaDetailActivity,
                            this@MilitaryEncyclopediaDetailActivity
                        )
                }
                fontResizeDialog?.show()
            }
        })
    }

    var fontResizeDialog: FontResizeDialog? = null
    var fontShare: ShareWrap? = null

    override fun toggleTitleBar(open: Boolean) {
        super.toggleTitleBar(open)
        fontShare = ShareWrap(this, false)
        fontShare?.setShowFunction(true)
        textSizeCtl.setImageResource(R.drawable.imagetext_more)

        if (open) {
            textSizeCtl.visibility = View.VISIBLE
            textSizeCtl.setOnClickListener {
                fontShare?.show(it)
            }
        } else {
            textSizeCtl.visibility = View.GONE
        }
    }

    override fun openTitleBarSetting(): Boolean {
        return true
    }

    var lastLevel = -1

    override fun onFontChange(levelIndex: Int) {
        if (levelIndex == lastLevel) {
            return
        }
        lastLevel = levelIndex
        val zoom = AppConfig.zoomSize[levelIndex]!!
        resizeFont(levelIndex, zoom)
    }

    private fun resizeFont(levelIndex: Int, zoom: Int) {
        MMKV.defaultMMKV().putInt(XKey.MICRO_FONT_SIZE, levelIndex)
        val textSize24: Float = resources.getDimension(R.dimen.sp_24) * (zoom / 100f)
        val textSize15: Float = resources.getDimension(R.dimen.sp_15) * (zoom / 100f)
        tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize24)
        tvShortTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize15)
        val webSettings: WebSettings = webContent.settings
        webSettings.textZoom = zoom
        militaryEncyclopediaDirectoryRelationAdapter?.resizeText(zoom)
        militaryEncyclopediaInfoRelationAdapter?.resizeText(zoom)
        militaryEncyclopediaEntryRefAdapter?.resizeText(zoom)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun closeCurrent(event: WikiEvent) {
        finish()
    }

    var imageList: ArrayList<LocalMediaWithState> = arrayListOf()
    var imgAdapter: ErrorCorrectingAdapter? = null
    var errorCorrectingDialog: ErrorCorrectingDialog? = null

    val MAX = 9
    protected fun permissionsOK(type: Int) {
        var type = type
        if (type == PictureConfig.TYPE_IMAGE) {
            if (imageList.size > MAX) {
                ToastUtil.showCustomView(this, R.string.max_baoliao_plused)
                return
            }
            val imageLocalMediaList: MutableList<LocalMedia> = ArrayList()
            for (localMediaWithState in imageList) {
                imageLocalMediaList.add(localMediaWithState.localMedia)
            }
            PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(MAX)
                .imageSpanCount(3)
                .enableCrop(false)
                .cropCompressQuality(70)
                .compress(true)
                .minimumCompressSize(800)
                .isGif(true)
                .previewImage(false)
                .isCamera(true)
                .selectionMedia(imageLocalMediaList)
                .forResult(PictureConfig.TYPE_IMAGE)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null) {
            if (requestCode == PictureConfig.TYPE_IMAGE) {
                imageList.clear()
                val mediaList = PictureSelector.obtainMultipleResult(data)
                buildLocalMediaList(mediaList, imageList)
            }
            errorCorrectingDialog?.let {
                it.tvUpNum?.text = "(${imageList.size}/9)"
            }
            imgAdapter?.setSelectList(imageList)
        }
    }

    private fun buildLocalMediaList(
        mediaList: List<LocalMedia>?,
        videoList: MutableList<LocalMediaWithState>
    ) {
        if (mediaList != null && mediaList.size != 0) {
            for (localMedia in mediaList) {
                videoList.add(LocalMediaWithState(localMedia))
            }
        }
    }

    /**
     * 上传图片
     */
    private fun submitImage(content: String) {
        if (imageList.size == 0) {
            submitErrorCorrect(content)
            return
        }
        if (imageList.size > 0) {
            upImageLoadLocalMedia.clear()
            upImageLoadLocalMedia.addAll(imageList)
        }
        if (upImageLoadLocalMedia.size > 0) {
            fileList.clear()
            imageProgressMap.clear()
            if (upImageLoadLocalMedia[0].localMedia.isCompressed) {
                fileList[upImageLoadLocalMedia[0]] =
                    File(upImageLoadLocalMedia[0].localMedia.compressPath)
            } else {
                fileList[upImageLoadLocalMedia[0]] = File(upImageLoadLocalMedia[0].localMedia.path)
            }
            imageProgressMap[upImageLoadLocalMedia[0]] = Progress(
                upImageLoadLocalMedia[0], imgAdapter, imageList
            )
            upLoadImageSingle(content)
        }
    }

    var upImageLoadLocalMedia: MutableList<LocalMediaWithState> = ArrayList()
    var fileList: MutableMap<LocalMediaWithState, File> = HashMap()
    var imageProgressMap: MutableMap<LocalMediaWithState, UploadCallbacks> = HashMap()
    private val resourceModes: ArrayList<String> = arrayListOf()

    private fun upLoadImageSingle(content: String) {
        val map: MutableMap<String, RequestBody> = HashMap()
        map["TenantID"] = CMSApi.convertToRequestBody(getString(R.string.tenantid))
        Log.e(
            "upLoadImageSingle",
            (+fileList[upImageLoadLocalMedia[0]]!!.length() / 1024).toString() + "k " + fileList[upImageLoadLocalMedia[0]]!!
                .path
        )
        CMSApi.getBlApi()
            .uploadImg(map, CMSApi.filesToMultipartBodyParts(fileList, imageProgressMap))
            .enqueue(object : Callback<SubmitImageReturnData> {
                override fun onResponse(
                    call: Call<SubmitImageReturnData>,
                    response: Response<SubmitImageReturnData>
                ) {
                    try {
                        if (response.body()!!.state == 200) {
                            val data = response.body()!!.data
                            resourceModes.add(data[0].compressHttpUrl)
                            if (upImageLoadLocalMedia.size > 0) {
                                upImageLoadLocalMedia.removeAt(0)
                            }
                            if (upImageLoadLocalMedia.size > 0) {
                                fileList.clear()
                                imageProgressMap.clear()
                                imageProgressMap[upImageLoadLocalMedia[0]] =
                                    Progress(upImageLoadLocalMedia[0], imgAdapter, imageList)
                                if (upImageLoadLocalMedia[0].localMedia.isCompressed) {
                                    fileList[upImageLoadLocalMedia[0]] =
                                        File(upImageLoadLocalMedia[0].localMedia.compressPath)
                                } else {
                                    fileList[upImageLoadLocalMedia[0]] =
                                        File(upImageLoadLocalMedia[0].localMedia.path)
                                }
                                upLoadImageSingle(content)
                            }
                            if (resourceModes.size == imageList.size) {
                                submitErrorCorrect(content)
                            }
                        } else {
                            ToastUtil.showCustomView(this@MilitaryEncyclopediaDetailActivity,response.body()?.message)

                        }
                    } catch (e: Exception) {

                    }
                }

                override fun onFailure(call: Call<SubmitImageReturnData>, t: Throwable) {
                    Utility.showToast(this@MilitaryEncyclopediaDetailActivity, getString(R.string.baoliao_upload_image_fail))
                }
            })
    }

    class Progress(var localMedia: LocalMediaWithState,var adapter: ErrorCorrectingAdapter?,var imgList:ArrayList<LocalMediaWithState>) : UploadCallbacks {

        override fun onProgressUpdate(percentage: Int) {
            val position: Int = imgList.indexOf(localMedia)
            if(position != -1) {
                adapter?.getSelectList()?.get(position)?.setProgress(percentage)
                adapter?.notifyDataSetChanged()
            }
        }

        override fun onError() {
        }

        override fun onFinish() {
            val position: Int = imgList.indexOf(localMedia)
            if(position != -1){
                adapter?.getSelectList()?.get(position)?.progress = 100
                adapter?.getSelectList()?.get(position)?.isState = true
                adapter?.notifyDataSetChanged()
            }
        }
    }

    override fun finish() {
        super.finish()
        if (articleItem != null && mTyReportStartTime > 0) {
            mTyReportEndTime = System.currentTimeMillis()
            val globalRect = Rect();
            introduceRv.getGlobalVisibleRect(globalRect)
        }

    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }

    @JavascriptInterface
    fun openDialog(id:String) {
        entryRefList?.let{
            it.forEach {
                if (it.refId == id.toLongOrNull()){
                    MarkingDialog.Builder().builder(this)
                        .setTitle("[${it.refId}]${it.articleTitle}. ${it.websiteName}")
                        .setMsg("[发表日期${it.publishDate}]")
                        .setClick {view->
                            WebViewPageActivity.start(
                                it.websiteName,
                                it.websiteUrl,
                                this@MilitaryEncyclopediaDetailActivity
                            )
                        }
                        .create().show()
                }
            }
        }
        linkRelationList?.let{
            it.forEach {
                if (it.articleId == id.toLongOrNull()){
                    MarkingDialog.Builder().builder(this)
                        .setTitle(it.title)
                        .setMsg(it.shortTitle)
                        .setClick {view->
                            articleItem.id = it.articleId
                            articleItem.isCloseActivity = false
                            NewsItemClickUtils.OpenItemNewsHandle(view.context, articleItem.type, articleItem, null)
                        }
                        .create().show()
                }
            }
        }
    }

    fun parseHtml(html: String) {
        webContent.settings.javaScriptEnabled = true
        webContent.addJavascriptInterface(this, "ClickTip")
        webContent.setWebViewClient(object :WebBrowser.WebClient(this,webContent){
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                return true
            }
        })
        val doc = Jsoup.parse(html)
        val bodyNode: Elements? = doc.getElementsByTag("head")
        if (bodyNode != null && bodyNode.size > 0) {
            bodyNode[0].append("\n<script src=\"file:///android_asset/web/webnews.txt\"/>")
        }
        val aTags = doc.getElementsByTag("a")
        for (i in 0 until aTags.size) {
            val aElement = aTags[i]
            //href为空时，点击之后文本会消失，处理一下
            aElement.attr("href","https://baidu.com")
            aElement.attr("onclick", "wikiContentClick(this)")
        }
        var result = doc.toString()
        webContent.loadDataWithBaseURL(
            null,
            HtmlFormat.getNewContent(result),
            "text/html; charset=utf-8",
            "utf-8",
            null
        )

    }
}